/**
 * Created by zhangzhichao on 2016/11/16.
 */
/* eslint-disable no-unused-vars */
import _findIndex from "lodash/findIndex";
import state from "../libs/status";
import moment from "moment";
const digitsRE = /(\d{3})(?=\d)/g;

export function currency(value, currency, decimals) {
  value = parseFloat(value);
  if (!isFinite(value) || (!value && value !== 0)) return "";
  currency = currency != null ? currency : "$";
  decimals = decimals != null ? decimals : 2;
  var stringified = Math.abs(value).toFixed(decimals);
  var _int = decimals ? stringified.slice(0, -1 - decimals) : stringified;
  var i = _int.length % 3;
  var head = i > 0 ? _int.slice(0, i) + (_int.length > 3 ? "," : "") : "";
  var _float = decimals ? stringified.slice(-1 - decimals) : "";
  var sign = value < 0 ? "-" : "";
  return (
    sign + currency + head + _int.slice(i).replace(digitsRE, "$1,") + _float
  );
}

export function formatTime(date, format) {
  return moment(date).format(format);
}
export function formatRate(rate) {
  return rate * 100 + "%";
}
export function keyText(key, stateKey) {
  if (key || key !== undefined || key !== "") {
    const index = _findIndex(state[stateKey], o => o.value === key);
    if (index >= 0) {
      return state[stateKey][index].text;
    } else {
      return "";
    }
  } else {
    return "";
  }
}

export function fullImagePath(uri) {
  if (uri) {
    if (
      uri.indexOf("http") === 0 ||
      uri.indexOf("../") === 0 ||
      uri.indexOf("data:") === 0
    ) {
      return uri;
    } else {
      return window.api.imageDomain + uri;
    }
  } else {
    return "";
  }
}
